package event;

import java.io.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class FileReAndWrUtil {

    /**
     * 读取文件
     * @param file
     * @return
     */
    public static Set<String> readFile(File file){
        Set<String> set = new HashSet<>();
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String data = null;
            while ((data = bufferedReader.readLine()) != null){
                set.add(data);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
                inputStreamReader.close();
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return set;
    }

    /**
     * 写出文件
     * @param file
     * @param set
     */
    public static void writeFile(File file, Set<String> set){
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()){
                String str = iterator.next();
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedWriter.close();
                fileWriter.close();
            }
             catch (IOException e) {
                e.printStackTrace();
             }
        }

    }
}
